package one.stand.controller;

import com.github.pagehelper.PageHelper;
import com.jmp.api.admin.dto.*;
import com.jmp.autocofiguration.web.interceptor.SecurityAuthCheck;
import com.jmp.feign.TicketFeign;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import one.stand.dto.Company2Dto;
import one.stand.dto.ConvertUtils;
import one.stand.dto.PageResponse2;
import one.stand.dto.UserDto;
import one.stand.mapper.CompanyApiAdminMapper;
import one.stand.model.*;
import one.stand.service.BusinessCardBaseService;
import one.stand.service.CompanyBaseService;
import one.stand.service.user.UserAdminService;
import one.stand.util.AssertUtil;
import one.stand.util.DownLoadExcelUtil;
import one.stand.util.SqlUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Objects;

/**
 * @author cjr
 */
@Api("奖券管理")
@RestController
@RequestMapping("adminApi/ticket")
public class TicketController {
    @Autowired
    private TicketFeign ticketFeign;
    @Autowired
    private UserAdminService userAdminService;
    @Autowired
    private CompanyBaseService companyBaseService;
    @Autowired
    private BusinessCardBaseService businessCardBaseService;

    @Autowired
    private CompanyApiAdminMapper companyApiAdminMapper;

    @ApiOperation("列表")
    @GetMapping("")
    @SecurityAuthCheck
    public ResultModel<TicketListResponse> list(TicketListRequest request) {

        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        List<TicketListResponse.Ticket> tickets = companyApiAdminMapper.selectTicketList(SqlUtil.like(request.getKeyword()), request.getStatus());
        PageResponse2<TicketListResponse.Ticket> ticketPageResponse2 = ConvertUtils.page2(tickets, ticket -> {
            ticket.setCheckUserName(userAdminService.get(ticket.getCheckUser()).getName());
            ticket.setUserName(userAdminService.get(ticket.getUserId()).getName());
            return ticket;
        });

        TicketListResponse response = TicketListResponse.builder()
                .tickets(ticketPageResponse2)
                .build();
        return ResultModel.success(response);
    }

    @ApiOperation("列表导出")
    @GetMapping("download")
    @SecurityAuthCheck
    public void download(TicketListRequest request, HttpServletResponse response) throws IOException {

        List<TicketListResponse.Ticket> tickets = companyApiAdminMapper.selectTicketList(SqlUtil.like(request.getKeyword()), request.getStatus());
        List<TicketListDownloadResponse> data = ConvertUtils.list(tickets, order -> {
            return TicketListDownloadResponse.builder()
                    .id(order.getId())
                    .userName(userAdminService.get(order.getUserId()).getName())
                    .companyName(order.getCompanyName())
                    .phone(order.getPhone())
                    .money(order.getMoney())
                    .orderNum(order.getOrderNum())
                    .num(order.getNum())
                    .status(order.getStatus() == 1 ? "已核销" : "未核销")
                    .checkTime(order.getCheckTime())
                    .checkUserName(userAdminService.get(order.getCheckUser()).getName())
                    .build();
        });
        DownLoadExcelUtil.download(response, "奖券", "订单", TicketListDownloadResponse.class, data);
    }

    @ApiOperation("订单明细")
    @GetMapping("detail/order")
    @SecurityAuthCheck
    public ResultModel<TicketOrderCompanyDetailResponse> order(TicketDetailOrderRequest request) {

        UserDto user = userAdminService.get(request.getUserId());
        BusinessCard card = businessCardBaseService.getByUserId(request.getUserId());
        String companyName = null;
        String companyUser = null;
        String companyTel = null;
        if (Objects.nonNull(card)) {
            Company2Dto company = companyBaseService.get2(card.getCompanyId());
            companyName = company.getCompanyName();
            BusinessCard businessCard = businessCardBaseService.getByUserId(request.getUserId());
            companyUser = StringUtils.isNoneBlank(company.getUserName()) ? company.getCompanyName() : businessCard.getName();
            companyTel = StringUtils.isNoneBlank(company.getPhone()) ? company.getPhone() : businessCard.getPhone();
        }

        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        List<TicketOrderCompanyDetailResponse.Order> orders = companyApiAdminMapper.selectTicketOrderDetailList(request.getUserId(), request.getStatus());
        PageResponse2<TicketOrderCompanyDetailResponse.Order> orderPageResponse2 = ConvertUtils.page2(orders, ticket -> {
            if (StringUtils.isNoneBlank(ticket.getAuditor())) {
                ticket.setAuditor(userAdminService.get(Integer.valueOf(ticket.getAuditor())).getName());
            }
            return ticket;
        });
        TicketOrderCompanyDetailResponse response = TicketOrderCompanyDetailResponse.builder()
                .createName(user.getName())
                .companyName(companyName)
                .companyUser(companyUser)
                .companyTel(companyTel)
                .orders(orderPageResponse2)
                .build();
        return ResultModel.success(response);
    }

    @ApiOperation("订单明细-导出")
    @GetMapping("detail/order/download")
    @SecurityAuthCheck
    public void orderDownload(TicketDetailOrderRequest request, HttpServletResponse response) throws IOException {

        List<TicketOrderCompanyDetailResponse.Order> orders = companyApiAdminMapper.selectTicketOrderDetailList(request.getUserId(), request.getStatus());
        List<TicketOrderCompanyDetailDownloadResponse> data = ConvertUtils.list(orders, order -> {
            if (StringUtils.isNoneBlank(order.getAuditor())) {
                order.setAuditor(userAdminService.get(Integer.valueOf(order.getAuditor())).getName());
            }
            return TicketOrderCompanyDetailDownloadResponse.builder()
                    .orderNo(order.getOrderNo())
                    .orderMoney(order.getOrderMoney())
                    .companyName(order.getCompanyName())
                    .type(order.getType())
                    .addr(order.getAddr())
                    .ctime(order.getCtime())
                    .auditor(order.getAuditor())
                    .status(order.getStatus() == 1 ? "已通过" : (order.getStatus() == 2 ? "未通过" : "审核中"))
                    .memo(StringUtils.defaultIfBlank(order.getMemo(), StringUtils.EMPTY))
                    .build();
        });
        DownLoadExcelUtil.download(response, "订单明细", "订单", TicketOrderCompanyDetailDownloadResponse.class, data);
    }

    @ApiOperation("核销:奖券详情")
    @PostMapping("info")
    @SecurityAuthCheck
    public ResultModel<com.jmp.api.admin.dto.TicketInfoResponse> info(@RequestBody TicketInfoRequest request) {

        ResultModel<com.jmp.service.api.admin.dto.TicketInfoResponse> infoResponseResultModel = ticketFeign.info(com.jmp.service.api.admin.dto.TicketInfoRequest.builder().qrCode(request.getQrCode()).build());
        AssertUtil.isTrue(infoResponseResultModel);

        com.jmp.service.api.admin.dto.TicketInfoResponse infoResponse = infoResponseResultModel.getData();
        UserDto orderUser = userAdminService.get(infoResponse.getUserId());

        com.jmp.api.admin.dto.TicketInfoResponse response = com.jmp.api.admin.dto.TicketInfoResponse.builder()
                .companyName(orderUser.getName())
                .phone(orderUser.getPhone())
                .status(infoResponse.getStatus())
                .money(infoResponse.getOrderMoney())
                .orderNum(infoResponse.getOrderNum())
                .num(infoResponse.getNum())
                .checkTime(infoResponse.getCheckTime())
                .checkUserName(userAdminService.get(infoResponse.getCheckUser()).getName())
                .build();

        return ResultModel.success(response);
    }

    @ApiOperation("核销")
    @PostMapping("use")
    @SecurityAuthCheck
    public ResultModel use(@RequestBody TicketUseRequest request) {

        ResultModel resultModel = ticketFeign.use(com.jmp.service.api.admin.dto.TicketUseRequest.builder()
                .qrCode(request.getQrCode())
                .build());
        AssertUtil.isTrue(resultModel);

        return ResultModel.success();
    }
}
